---
title: 'subscribe'
section: 'API'
subSection: 'Advanced'
description: 'Subscribe to a current state/object'
---

# `subscribe`

## Subscribe from anywhere

You can access state outside your components and subscribe to changes.

```jsx
import { proxy, subscribe } from 'valtio'

const state = proxy({ count: 0 })

// Subscribe to all changes to the state proxy (and its child proxies)
const unsubscribe = subscribe(state, () =>
  console.log('state has changed to', state),
)
// Unsubscribe by calling the result
unsubscribe()
```

You can also subscribe to a portion of state.

```jsx
const state = proxy({ obj: { foo: 'bar' }, arr: ['hello'] })

subscribe(state.obj, () => console.log('state.obj has changed to', state.obj))
state.obj.foo = 'baz'
subscribe(state.arr, () => console.log('state.arr has changed to', state.arr))
state.arr.push('world')
```

## Codesandbox demo in VanillaJS

https://codesandbox.io/s/valtio-photo-booth-demo-forked-xp8hs?file=/src/main.js
